package com.cloudshop.service.common.log;

import java.util.Date;
import org.springframework.stereotype.Component;

/**
 * 日志管理类.
 *
 * @author 宫新程
 * @since 2019/3/29 21:39
 */
@Component
public class LogManager {

  private static final ThreadLocal<GlobalAccessLog> logLocal = new ThreadLocal<>();

  /** 设置 过滤器 层参数. */
  public static void filterInit(
      String projectName,
      String hostName,
      String httpMethod,
      String requestId,
      String userAgent,
      String fromSystem,
      String domainName,
      String clientIp,
      String token,
      String userId,
      String userName,
      String uri) {
    GlobalAccessLog log = buildGlobalAccessLog(projectName, hostName, requestId);
    log.setUserAgent(userAgent);
    log.setFromSystem(fromSystem);
    log.setDomainName(domainName);
    log.setClientIp(clientIp);
    log.setUri(uri);
    log.setHttpMethod(httpMethod);
    log.setToken(token);
    log.setUserId(userId);
    log.setUserName(userName);
    logLocal.set(log);
  }

  /** 设置 Controller 层使用AOP获取的参数. */
  public static void aspectInit(String className, String methodName, String methodParams) {
    GlobalAccessLog log = logLocal.get();
    log.setClassName(className);
    log.setMethodName(methodName);
    log.setMethodParams(methodParams);
  }

  /** 设置结束时间. */
  public static void setEndTime(Date endTime) {
    GlobalAccessLog log = logLocal.get();
    log.setEndTime(endTime);
  }

  /** 设置Controller层消耗时间. */
  public static void setConsume(long consume) {
    GlobalAccessLog log = logLocal.get();
    log.setConsume(consume);
  }

  /** 设置异常信息. */
  public static void setException(String exception) {
    GlobalAccessLog log = logLocal.get();
    log.setException(exception);
  }

  /** 设置响应编码. */
  public static void setHttpStatus(Integer httpStatus) {
    GlobalAccessLog log = logLocal.get();
    log.setHttpStatus(httpStatus);
  }

  /** 初始化dto. */
  private static GlobalAccessLog buildGlobalAccessLog(
      String projectName, String hostName, String requestId) {
    GlobalAccessLog log = new GlobalAccessLog();
    log.setStartTime(new Date());
    log.setProjectName(projectName);
    log.setHostName(hostName);
    log.setRequestId(requestId);
    return log;
  }

  /** 获取日志信息. */
  public static GlobalAccessLog getGlobalAccessLog() {
    return logLocal.get();
  }
}
